package main

import (
	"bufio"
	"io"
	"io/ioutil"
	"os"
	"strconv"
	"time"

	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

// BlockInfo 块信息
type BlockInfo struct {
	IP        string              `json:"ip"`
	BlockID   int                 `json:"blockid"`
	CreatTime bson.MongoTimestamp `json:"creattime"`
	Data      interface{}         `json:"data"`
}

// LogInfo 日志信息
type LogInfo struct {
	IP        string              `json:"ip"`
	CreatTime bson.MongoTimestamp `json:"creattime"`
	Data      interface{}         `json:"data"`
}

// URL 数据库链接地址
const (
	URL                 string = "mongodb://root:!Q2w3e$R@180.101.204.40:27017"
	DBName              string = "chain"
	CollectionNameBlock string = "block"
	CollectionNameLog   string = "log"

	IPPath        string = "/chain/AGENT_IP"
	DataBlockPath string = "/chain/data/finalblock"

	DataLogName string = "/chain/LOGNAME"
	DataLogPath string = "/chain/data/finallogs"
)

func main() {

	session, err := mgo.Dial(URL) //连接数据库
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	db := session.DB(DBName)                     //数据库名称
	collectionBlock := db.C(CollectionNameBlock) //如果该集合已经存在的话，则直接返回
	collectionLog := db.C(CollectionNameLog)     //如果该集合已经存在的话，则直接返回

	//*******构造数据*******
	var blockinfo BlockInfo

	blockinfo.IP = readstring(IPPath)
	blockinfo.BlockID = 0

	for {
		blockinfo.CreatTime = bson.MongoTimestamp(time.Now().Unix())

		datap := DataBlockPath + strconv.Itoa(blockinfo.BlockID)
		if !isExist(datap) {
			time.Sleep(1)
			break
		}

		var f interface{}
		data := readbyte(datap)
		bson.UnmarshalJSON(data, &f)
		blockinfo.Data = f
		err = collectionBlock.Insert(&blockinfo)
		if err != nil {
			panic(err)
		}
		blockinfo.BlockID++
	}

	//*******构造数据*******
	//	copyFile(DataLogPath, readstring(DataLogName))
	var logInfo LogInfo
	logInfo.IP = readstring(IPPath)

	f, err := os.Open(DataLogPath)
	defer f.Close()
	if nil == err {
		buff := bufio.NewReader(f)
		for {
			line, err := buff.ReadString('\n')
			if err != nil || io.EOF == err {
				break
			}
			logInfo.CreatTime = bson.MongoTimestamp(time.Now().Unix())
			var f1 interface{}
			bson.UnmarshalJSON([]byte(line), &f1)
			logInfo.Data = f1
			err = collectionLog.Insert(&logInfo)
			if err != nil {
				panic(err)
			}
		}
	}

}
func readstring(path string) string {
	fi, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err := ioutil.ReadAll(fi)
	return string(fd)
}
func readbyte(path string) []byte {
	fi, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err := ioutil.ReadAll(fi)
	return fd
}
func isExist(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}
func copyFile(dstName, srcName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		return
	}
	defer src.Close()
	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return
	}
	defer dst.Close()
	return io.Copy(dst, src)
}
